﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Chat.Models.Services;
using Chat.Models;

namespace Chat.Models.Services
{
    public class ChatMessageService
    {
        static public List<ChatMessages> getChatMessagesWithFriend(int UserId, int FriendId)
        {
            var db = new chatEntities();
            var res = (from item in db.ChatMessages
                       where item.SenderID == UserId && item.ReceiverID == FriendId ||
                            item.SenderID == FriendId && item.ReceiverID == UserId
                       orderby item.MessageID 
                       select item);
            return res.ToList();
        }

        static public ChatMessages GetLastChatMessage(int senderID, int receiverID)
        {
            var db = new chatEntities();
            var res = (from item in db.ChatMessages
                       where item.SenderID == senderID && item.ReceiverID == receiverID||
                            item.SenderID == receiverID && item.ReceiverID == senderID
                       orderby item.MessageID descending
                       select item);
            if(res.Count() > 0)
            {
                return res.First();
            }
            return null;
        }

        static public bool  addChatMessage(ChatMessages chatMessageMoudel)
        {
            try
            {
                var db = new chatEntities();
                ChatMessages chatMessage = new ChatMessages();


                var friendship = UserService.GetFriendshipsByUserIDAAndUserB(chatMessageMoudel.SenderID, chatMessageMoudel.ReceiverID);
                if (friendship == null) return false;


                chatMessage.SenderID = chatMessageMoudel.SenderID;
                chatMessage.ReceiverID = chatMessageMoudel.ReceiverID;
                chatMessage.MessageType = chatMessageMoudel.MessageType;
                chatMessage.MessageText = chatMessageMoudel.MessageText;
                chatMessage.Timestamp = DateTime.Now;

                db.ChatMessages.Add(chatMessage);
                db.SaveChanges();

                return true;
            }
            catch
            {
                return false;
            }
        }
        
    }
}